<?php
// +----------------------------------------------------------------------
// | WWW.0771MC.COM 广西南宁市铭成龙毅网络科技有限公司 出品
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://WWW.0771MC.COM All rights reserved.
// +----------------------------------------------------------------------
// | Author: 铭成龙毅 <service@0771mc.com> <http://www.0771MC.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Think\Controller;

class DownloadController extends CommonController
{

    //下载文档列表
    public function index()
    {

        $pid = I('get.pid', 0, 'intval');
        $keyword = I('keyword', '', 'htmlspecialchars,trim');
        $Category = new \Think\Category();
        //$cate = D('CategoryView')->order('category.sort')->select();
        $cate = getCategory();
        $this->subcate = $Category::getChilds($cate, $pid);
        $this->poscate = $Category::getParents($cate, $pid);
        if ($pid) {
            $idarr = $Category::getChildsId($cate, $pid, 1);
            $where = array('download.status' => 0, 'cid' => array('in', $idarr));
        } else {
            $where = array('download.status' => 0);
        }
        if (!empty($keyword)) {
            $where['download.title'] = array('LIKE', "%{$keyword}%");
        }
        $pageSize = I('pageSize', 15, 'intval');
        $pageCurrent = I('pageCurrent', 1, 'intval');
        $count = D('DownloadView')->where($where)->count();
        $startCount = ($pageCurrent - 1) * $pageSize;
        $page = new \Think\Page($count, $pageSize);
        $limit = $startCount . ',' . $pageSize;
        $art = D('DownloadView')->where($where)->order('download.id DESC')->limit($limit)->select();
        $this->pid = $pid;
        $this->keyword = $keyword;
        $this->page = $page->show();
        $this->vlist = $art;
        $this->totalRows = $page->totalRows;
        $this->nowPage = $page->nowPage;
        $this->display();
    }

    //增加
    public function add()
    {


        //当前控制器名称       
        $actionName = strtolower($Think . CONTROLLER_NAME);
        $this->pid = I('pid', 0, 'intval');

        if (IS_POST) {


            $this->addPost();
            exit();
        }


        $cate = getCategory(2);
        $Category = new \Think\Category();
        $cate = $Category::unlimitedForLevel($cate);
        $this->softtypelist = getArrayOfItem('softtype');
        $this->softlanguage = getArrayOfItem('softlanguage');
        $this->type = "添加文档下载";
        $this->cate = $Category::getLevelOfModel($cate, $actionName);
        $this->flagtypelist = getArrayOfItem('flagtype'); //文档属性
        $this->display();
    }


    //处理添加下载
    public function addPost()
    {

        $pid = I('pid', 0, 'intval');
        $cid = I('cid', 0, 'intval');
        $title = I('title', '', 'htmlspecialchars,rtrim');
        $flags = I('flags', array(), 'intval');

        $description = I('description', '');
        $downlink = I('downlink', '');
        $content = I('content', '', '');
        $pic = I('litpic', '', 'htmlspecialchars,trim');
        $updatetime = I('updatetime', time(), 'strtotime');
        if (empty($title)) {
            error('名称不能为空');
        }
        if (!$cid) {
            error('请选择栏目');
        }
        $pid = $cid; //转到自己的栏目       

        if (empty($description)) {
            $description = str2sub(strip_tags($content), 120);
        }

        //图片标志
        if (!empty($pic) && !in_array(B_PIC, $flags)) {
            $flags[] = B_PIC;
        }
        $flag = implode(',', $flags); //拼装属性

        $downlink = str_replace("\n", '|||', $downlink);


        //获取属于分类信息,得到modelid
        $Category = new \Think\Category();
        $selfCate = $Category::getSelf(getCategory(0), $cid); //当前栏目信息
        $modelid = $selfCate['modelid'];

        //内容中的图片
        $img_arr = array();
        $reg = "/<img[^>]*src=\"((.+)\/(.+)\.(jpg|gif|bmp|png))\"/isU";
        preg_match_all($reg, $content, $img_arr, PREG_PATTERN_ORDER);
        // 匹配出来的不重复图片
        $img_arr = array_unique($img_arr[1]);
        if (empty($pic)) {
            $pic = $img_arr[0];
        }


        $data = array(
            'title' => $title,
            'color' => I('color', 'htmlspecialchars,trim'),
            'filesize' => I('filesize', '', 'htmlspecialchars,trim'),
            'downlink' => $downlink,
            'cid' => $cid,
            'litpic' => $pic,
            'keywords' => I('keywords', '', 'htmlspecialchars,trim'),
            'description' => $description,
            'content' => $content,
            'publishtime' => I('publishtime', time(), 'strtotime'),
            'updatetime' => $updatetime,
            'click' => rand(10, 95),
            'status' => 0,
            'commentflag' => I('commentflag', 0, 'intval'),
            'flag' => $flag,
            'aid' => $_SESSION['aid']

        );

        if ($id = M('download')->add($data)) {

            //更新上传附件表
            if (!empty($pic)) {
                //$pic = preg_replace('/!(\d+)X(\d+)\.jpg$/i', '', $pic);
                $attid = M('attachment')->where(array('filepath' => $pic))->getField('id');
                if ($attid) {
                    M('attachmentindex')->add(array('attid' => $attid, 'arcid' => $id, 'modelid' => $modelid));
                }
            }


            if (!empty($img_arr)) {
                $attid = M('attachment')->where(array('filepath' => array('in', $img_arr)))->getField('id', true);
                $dataAtt = array();
                if ($attid) {
                    foreach ($attid as $v) {
                        $dataAtt[] = array('attid' => $v, 'arcid' => $id, 'modelid' => $modelid);
                    }
                    M('attachmentindex')->addAll($dataAtt);
                }

            }


            //更新静态缓存
            delCacheHtml('List/index_' . $cid, false, 'list:index');
            delCacheHtml('Index_index', false, 'index:index');

            // $this->success('添加成功',U('Download/index', array('pid' => $pid)));
            yes('添加成功！', true, 'article-index');
        } else {
            error('添加失败');
        }
    }

    //编辑文章
    public function edit()
    {
        //当前控制器名称
        $id = I('id', 0, 'intval');
        $actionName = strtolower($Think . CONTROLLER_NAME);
        $this->pid = I('pid', 0, 'intval');

        if (IS_POST) {
            $this->editPost();
            exit();
        }

        $cate = getCategory(2);
        $Category = new \Think\Category();
        $cate = $Category::unlimitedForLevel($cate);
        $this->cate = $Category::getLevelOfModel($cate, $actionName);

        $this->softtypelist = getArrayOfItem('softtype');
        $this->softlanguage = getArrayOfItem('softlanguage');
        $vo = M($actionName)->find($id);
        $vo['downlink'] = str_replace('|||', "\n", $vo['downlink']);
        $vo['content'] = htmlspecialchars($vo['content']);
        $vo['flag'] = explode(',', $vo['flag']);

        $this->vo = $vo;
        $this->flagtypelist = getArrayOfItem('flagtype'); //文档属性
        $this->type = '修改文档下载';
        $this->display();
    }


    //修改文章处理
    public function editPost()
    {

        $data = array(
            'id' => I('id', 0, 'intval'),
            'title' => I('title', '', 'htmlspecialchars,rtrim'),
            'color' => I('color', 'htmlspecialchars,trim'),

            'filesize' => I('filesize', '', 'htmlspecialchars,trim'),
            'downlink' => I('downlink', ''),

            'cid' => I('cid', 0, 'intval'),
            'litpic' => I('litpic', ''),
            'keywords' => I('keywords', '', 'htmlspecialchars,trim'),
            'description' => I('description', '', 'htmlspecialchars,trim'),
            'content' => I('content', '', ''),

            'publishtime' => I('publishtime', time(), 'strtotime'),
            'updatetime' => I('updatetime', time(), 'strtotime'),
            'commentflag' => I('commentflag', 0, 'intval'),

        );

        $id = $data['id'];
        $pid = I('pid', 0, 'intval');
        $flags = I('flags', array(), 'intval');
        $pic = $data['litpic'];

        if (empty($data['title'])) {
            error('标题不能为空');
        }
        if (!$data['cid']) {
            error('请选择栏目');
        }
        $pid = $data['cid']; //转到自己的栏目

        if (empty($data['description'])) {
            $data['description'] = str2sub(strip_tags($data['content']), 120);
        }


        //图片标志
        if (!empty($pic) && !in_array(B_PIC, $flags)) {
            $flags[] = B_PIC;
        }

        $data['flag'] = implode(',', $flags); //拼装属性


        $data['downlink'] = str_replace("\n", '|||', $data['downlink']);


        //获取属于分类信息,得到modelid
        $Category = new \Think\Category();
        $selfCate = $Category::getSelf(getCategory(0), $data['cid']); //当前栏目信息
        $modelid = $selfCate['modelid'];

        //内容中的图片
        $img_arr = array();
        $reg = "/<img[^>]*src=\"((.+)\/(.+)\.(jpg|gif|bmp|png))\"/isU";
        preg_match_all($reg, $data['content'], $img_arr, PREG_PATTERN_ORDER);
        // 匹配出来的不重复图片
        $img_arr = array_unique($img_arr[1]);
        if (empty($pic)) {
            $data['litpic'] = $img_arr[0];
        }


        if (false !== M('Download')->save($data)) {
            //del
            M('attachmentindex')->where(array('arcid' => $id, 'modelid' => $modelid))->delete();

            //更新上传附件表
            if (!empty($pic)) {
                //$pic = preg_replace('/!(\d+)X(\d+)\.jpg$/i', '', $pic);//清除缩略图的!200X200.jpg后缀
                $attid = M('attachment')->where(array('filepath' => $pic))->getField('id');
                if ($attid) {
                    M('attachmentindex')->add(array('attid' => $attid, 'arcid' => $id, 'modelid' => $modelid));
                }
            }


            if (!empty($img_arr)) {
                $attid = M('attachment')->where(array('filepath' => array('in', $img_arr)))->getField('id', true);
                $dataAtt = array();
                if ($attid) {
                    foreach ($attid as $v) {
                        $dataAtt[] = array('attid' => $v, 'arcid' => $id, 'modelid' => $modelid);
                    }
                    M('attachmentindex')->addAll($dataAtt);
                }

            }

            //更新静态缓存
            delCacheHtml('List/index_' . $data['cid'] . '_', false, 'list:index');
            delCacheHtml('List/index_' . $selfCate['ename'], false, 'list:index'); //还有只有名称
            delCacheHtml('Show/index_*_' . $id, false, 'show:index'); //不太精确，会删除其他模块同id文档     

            // $this->success('修改成功', U('Download/index', array('pid' => $pid)));
            yes('修改成功！', true, 'article-index');
        } else {

            error('修改失败');
        }

    }


    //回收站文章列表
    public function trach()
    {
        $where = array('download.status' => 1);
        $pageSize = I('pageSize', 15, 'intval');
        $pageCurrent = I('pageCurrent', 1, 'intval');
        $count = D('DownloadView')->where($where)->count();
        $startCount = ($pageCurrent - 1) * $pageSize;
        $page = new \Think\Page($count, $pageSize);
        $limit = $startCount . ',' . $pageSize;
        $art = D('DownloadView')->where($where)->order('id desc')->limit($limit)->select();
        $this->pid = I('pid', 0, 'intval');
        $this->page = $page->show();
        $this->vlist = $art;
        $this->subcate = '';
        $this->totalRows = $page->totalRows;
        $this->nowPage = $page->nowPage;
        $this->display('index');
    }

    //删除文章到回收站  兼容三个地方删除操作
    public function del()
    {
        $pid = I('get.pid', 0, 'intval');
        if (IS_POST) {
            $id = I('get.id'); //顶部删除
            if (empty($id)) {
                $idArr = I('post.id'); //右下角删除
            } else {
                $idArr = explode(',', $id);
            }
        } else { //点击删除
            $idArr = I('id', 0, 'intval');
            $idArr = array($idArr);
        }
        if ($idArr[0] == 0 || $idArr == 0) {
            error('没有选择删除项！');
        }
        if (M('download')->where(array('id' => array('in', $idArr)))->setField('status', 1)) {
            foreach ($idArr as $v) {
                delCacheHtml('Show/index_*_' . $v . '.', false, 'show:index');
            }
            yes('删除成功');
        } else {
            error('删除失败');
        }
    }


    //还原文章
    public function restore()
    {
        $pid = I('get.pid', 0, 'intval');
        if (IS_POST) {
            $id = I('get.id');
            $idArr = explode(',', $id);
        } else {
            $idArr = I('id', 0, 'intval');
            $idArr = array($idArr);
        }
        if (M('download')->where(array('id' => array('in', $idArr)))->setField('status', 0)) {
            yes('还原成功！', false, 'Download-index');
        } else {
            error('还原失败');
        }
    }


    //彻底删除文章
    public function clear()
    {
        $pid = I('get.pid', 0, 'intval');
        if (IS_POST) {
            $id = I('get.id');
            $idArr = explode(',', $id);
        } else {
            $idArr = I('id', 0, 'intval');
            $idArr = array($idArr);
        }
        $where = array('id' => array('in', $idArr));
        $modelid = D('DownloadView')->where(array('id' => $idArr[0]))->getField('modelid');

        if (M('download')->where($where)->delete()) {
            if ($modelid) {
                $where = array('arcid' => array('in', $idArr), 'modelid' => $modelid);
                $attid = M('attachmentindex')->where($where)->Field('attid')->select();
                $uid = arrToStr($attid);
                $map['id'] = array('exp', ' IN (' . $uid . ') ');
                $upath = M('attachment')->where($map)->Field('filepath')->select();
                foreach ($upath as $key => $value) {
                    @unlink('.' . $value['filepath']);
                }
                M('attachment')->where($map)->delete();
                M('attachmentindex')->where($where)->delete();
            }
            yes('彻底删除成功！');
        } else {
            error('彻底删除失败');
        }
    }


}

?>